package com.bdqn.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.common.utils.PageUtils;
import com.bdqn.common.utils.Query;
import com.bdqn.gulimall.product.dao.CategoryDao;
import com.bdqn.gulimall.product.entity.CategoryEntity;
import com.bdqn.gulimall.product.service.CategoryBrandRelationService;
import com.bdqn.gulimall.product.service.CategoryService;
import com.bdqn.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 三级分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());


        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否被别的地方引用


        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 找到catelogId的完整路劲
     * [父/子/孙]
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
//    @CacheEvict(value = "category",key = "'getLevel1Categorys'")  失效模式,更新之后，将缓存删除
//    @CachePut 双写模式，数据更新之后，再把最新数据往Redis存放一份最新的缓存
    //使用Caching执行批量操作
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'")
    })
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }


    /**
     * 查询1级分类
     *
     * @return
     */
    @Cacheable(value = "category",key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("没有缓存...");
        List<CategoryEntity> Level1List = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return Level1List;
    }

    /**
     * 查询出二级，三级分类
     *
     * @return catalogJsonDb
     */
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<Long, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询了数据库.....");
        /**
         * 1、将数据库的多次查询变为一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查询出所有的一级分类。
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);


        //2.封装数据
        Map<Long, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    List<CategoryEntity> level3Categorys = getParent_cid(selectList, l2.getCatId());
                    if (level3Categorys != null) {

                        List<Catelog2Vo.Catelog3Vo> collect = level3Categorys.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }


    // TODO: 2022/2/24 0024 高并发时可能会产生堆外内存溢出的错误 OutOfDirectMemoryError

    /**
     * 查询出二级，三级分类
     *
     * @return catalogJsonDb
     */
//    @Override
    public Map<Long, List<Catelog2Vo>> getCatalogJson2() {

        //取出redis中的数据
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");

        //判断是否有缓存,有就跳过，没有就新增缓存
        if (StringUtils.isEmpty(catalogJSON)) {
            Map<Long, List<Catelog2Vo>> catalogJsonDb = this.getCatalogJsonFromDbWithRedisLock();
            return catalogJsonDb;
        }

        //将JSON数据转换类型
        Map<Long, List<Catelog2Vo>> cacheResult = JSON.parseObject(catalogJSON, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
        });

        return cacheResult;
    }

    /**
     * 查询出二级，三级分类 分布式锁
     * 使用redis 的setEx  实现分布式锁，占到坑就拿到锁，可以去执行任务，执行完之后，释放锁，
     *
     * @return
     */
    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {


//            System.out.println("获取分布式锁成功.......");
//            //占锁成功，执行业务
//            Map<Long, List<Catelog2Vo>> dataFromDB=null;
//            try {
//                dataFromDB= getDataFromDB();
//            }finally {
//                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
//                        "then\n" +
//                        "    return redis.call(\"del\",KEYS[1])\n" +
//                        "else\n" +
//                        "    return 0\n" +
//                        "end";
//                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),
//                        Arrays.asList("lock"),uuid);
//            }
//            return dataFromDB;
        return null;
    }

    /**
     * 查询出二级，三级分类 分布式锁
     * 使用redis 的setEx  实现分布式锁，占到坑就拿到锁，可以去执行任务，执行完之后，释放锁，
     *
     * @return
     */
    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {

        String uuid = UUID.randomUUID().toString();
        //1.占分布式锁，去redis占坑
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功.......");
            //占锁成功，执行业务
            Map<Long, List<Catelog2Vo>> dataFromDB=null;
            try {
                 dataFromDB= getDataFromDB();
            }finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                        "then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),
                        Arrays.asList("lock"),uuid);
            }
            return dataFromDB;
        }else {
            //加锁失败...重试
            System.err.println("获取分布式锁失败.......");
            try {
                Thread.sleep(200);
            }catch (Exception e){

            }
            return getCatalogJsonFromDbWithRedisLock();    //自旋
        }
    }

    private Map<Long, List<Catelog2Vo>> getDataFromDB() {
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<Long, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<Long, List<Catelog2Vo>>>() {
            });
            return result;
        }

        System.out.println("查询了数据库.....");

        /**
         * 1、将数据库的多次查询变为一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查询出所有的一级分类。
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);


        //2.封装数据
        Map<Long, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    List<CategoryEntity> level3Categorys = getParent_cid(selectList, l2.getCatId());
                    if (level3Categorys != null) {

                        List<Catelog2Vo.Catelog3Vo> collect = level3Categorys.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }


    /**
     * 查询出二级，三级分类  本地锁测试
     *
     * @return
     */
    public Map<Long, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {


        /**
         * 1、将数据库的多次查询变为一次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查询出所有的一级分类。
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);


        //2.封装数据
        Map<Long, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    List<CategoryEntity> level3Categorys = getParent_cid(selectList, l2.getCatId());
                    if (level3Categorys != null) {

                        List<Catelog2Vo.Catelog3Vo> collect = level3Categorys.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;


    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、手机当前的节点
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}
